package com.atwisdom.star.core.dsl.modelClass.logic.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.UuidTool;
import com.atwisdom.star.common.vo.ModelType;
import com.atwisdom.star.common.vo.PageInfo;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstanceUtils;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierModel;
import com.atwisdom.star.core.dao.pojo.modelClass.logic.LogicInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.logic.LogicModel;
import com.atwisdom.star.core.dao.service.modelClass.logic.LogicInstanceHistoryService;
import com.atwisdom.star.core.dao.service.modelClass.logic.LogicInstanceService;
import com.atwisdom.star.core.dao.service.modelClass.logic.LogicModelService;
import com.atwisdom.star.core.dsl.cache.ModelCacheDslService;
import com.atwisdom.star.core.dsl.functionClass.BatchNumberDslService;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierModelDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.logic.LogicInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.utils.ListHier;
import com.atwisdom.star.core.dsl.modelClass.utils.ListHierContent;
import com.atwisdom.star.core.dsl.modelClass.utils.QueryBuilder;
import com.atwisdom.star.core.dsl.util.AutoGenUtil;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@AllArgsConstructor
@Service
@Slf4j
public class LogicInstanceDslServiceImpl implements LogicInstanceDslService {

    private LogicModelService logicModelService;
    private LogicInstanceService logicInstanceService;
    private LogicInstanceHistoryService logicInstanceHistoryService;
    private QueryBuilder queryBuilder;
    private ModelCacheDslService modelCacheDslService;
    private HierInstanceDslServiceImpl hierInstanceDslService;
    private HierModelDslServiceImpl hierModelDslService;
    private BatchNumberDslService batchNumberDslService;
    private AutoGenUtil autoGenUtil;

    /**
     * 查询全部摘要（通用）
     *
     * @return 返回搞要列表
     */
    @Override
    public List<JSONObject> queryAllInfo() {
        try {
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, null, "className,updateTime");
            List<LogicInstance> list = logicInstanceService.list();
            List<JSONObject> jsonObjectList = new ArrayList<>();
            list.forEach(ins -> jsonObjectList.add(ins.getInfoJsonObject()));
            return jsonObjectList;
        } catch (Exception ex) {
            throw new BusinessException("999999", "无条件查询所有模型信息！");
        }
    }

    /**
     * 分页查询全部摘要（通用）
     *
     * @param pageNumber 参数
     * @param pageSize   参数
     * @param orderBy    参数
     * @return 返回全部搞要列表
     */
    @Override
    public PageInfo queryAllInfoByPage(int pageNumber, int pageSize, String orderBy, boolean needHier) {
        try {
            Page<LogicInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper, true, needHier);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询摘要模型信息！", ex);
        }
    }

    /**
     * 查询全部数据（通用）
     *
     * @return 返回结果
     */
    @Override
    public List<JSONObject> queryAll() {
        try {
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryBuilder.buildOrderBy(queryWrapper, null, "className,updateTime");
            List<LogicInstance> list = logicInstanceService.list();
            list.forEach(l->{
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), l.getClassName(), l.getId());
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), l.getClassName());
                l.setHierModels(hierModels);
                l.setHierInstances(hierInstances);
            });

            return this.getLogicInsJsonObjectList(list);
        } catch (Exception ex) {
            throw new BusinessException("999999", "无条件查询所有模型信息！");
        }
    }

    /**
     * 分页无条件查询模型信息
     *
     * @param pageNumber 参数
     * @param pageSize   参数
     * @param orderBy    参数
     * @return 返回值
     */
    @Override
    public PageInfo listAllByPage(int pageNumber, int pageSize, String orderBy,  boolean needHier) {
        try {
            Page<LogicInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper, false, needHier);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 查询
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy   排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> query(String condition, String className, String orderBy) {
        try {
            List<LogicInstance> list = fetchInstanceList(condition, className, orderBy);
            list.forEach(l->{
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), l.getClassName(), l.getId());
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), l.getClassName());
                l.setHierInstances(hierInstances);
                l.setHierModels(hierModels);
            });
            return this.getLogicInsJsonObjectList(list);
        } catch (Exception ex) {
            throw new BusinessException("999999", "查询模型失败！", ex);
        }
    }

    /**
     * 查询，返回数据中不带hier
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy   排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> queryWithoutHier(String condition, String className, String orderBy) {
        List<LogicInstance> list = fetchInstanceList(condition, className, orderBy);
        return getLogicInsJsonObjectList(list);
    }

    /**
     * 查询，返回数据中不带hier
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @return 返回值
     */
    @Override
    public List<Long> queryIdWithoutHier(String condition, String className) {
        List<LogicInstance> list = fetchInstanceList(condition, className, null);
        List<Long> idList = list.stream().map(d -> d.getId()).collect(Collectors.toList());
        return idList;
    }


    /**
     * 查询模型
     * @param condition 查询参数
     * @param className
     * @return 返回值
     */
    @Override
    public List<JSONObject> query(String condition, String className) {
        return query(condition, className, null);
    }

    /**
     * 查询模型
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy   排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> query(String condition, String className, String orderBy, String hierValueCondition) {
        try {
            List<LogicInstance> list = fetchInstanceList(condition, className, orderBy);
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            long count = hierInstanceDslService.count(ModelType.Logic.getCode(), className, hierValueCondition);
            if (count > 0) {
                list.forEach(l->{
                    l.setHierInstances(null);
                    l.setHierModels(null);
                    l.setHier(null);
                    List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), l.getId(),  l.getClassName(), hierValueCondition);
                    List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), l.getClassName());
                    l.setHierInstances(hierInstances);
                    l.setHierModels(hierModels);
                });
            }
            return this.getLogicInsJsonObjectList(list);
        } catch (Exception ex) {
            throw new BusinessException("999999", "查询模型失败！", ex);
        }
    }



    /**
     * 查询模型
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy   排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> query(String condition, String className, String orderBy, String hierValueCondition,String parentId) {
        try {
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            List<LogicInstance> list = fetchInstanceList(condition, className, orderBy);
            long count = hierInstanceDslService.count(ModelType.Logic.getCode(), className, hierValueCondition,parentId);
            if (count > 0) {
                list.forEach(l->{
                    l.setHierInstances(null);
                    l.setHierModels(null);
                    l.setHier(null);
                    List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), l.getId(),  l.getClassName(), hierValueCondition);
                    List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), l.getClassName());
                    l.setHierInstances(hierInstances);
                    l.setHierModels(hierModels);
                });
            }
            return this.getLogicInsJsonObjectList(list);
        } catch (Exception ex) {
            throw new BusinessException("999999", "查询模型失败！", ex);
        }
    }

    private List<LogicInstance> fetchInstanceList(String condition, String className) {
        return fetchInstanceList(condition, className, null);
    }

    @Override
    public List<LogicInstance> fetchInstanceList(String condition, String className, String orderBy) {
        QueryWrapper<LogicInstance> queryWrapper = buildQueryWrapper(condition, className, orderBy);
        return logicInstanceService.list(queryWrapper);
    }

    @Override
    public long count(String condition, String className) {
        QueryWrapper<LogicInstance> queryWrapper = buildQueryWrapper(condition, className, null);
        return logicInstanceService.count(queryWrapper);
    }

    private QueryWrapper<LogicInstance> buildQueryWrapper(String condition, String className, String orderBy) {
        condition = queryBuilder.transformOperator(condition);
        condition = this.transformConditionForLogic(condition, className);
        orderBy = this.transformOrderByForLogic(condition, className, orderBy);
        QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
        queryWrapper.eq("published", true);
        queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
        queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
        return queryWrapper;
    }

    private List<LogicInstance> fetchInstanceList(String condition, String className, List<String> groupBy, String sumKey, String orderBy) {
        QueryWrapper<LogicInstance> queryWrapper = buildQueryWrapper(condition, className, orderBy);
        List<String> newGroupBy = transformConditionListForLogic(groupBy, className);
        queryWrapper.groupBy(CollectionUtil.isNotEmpty(newGroupBy), newGroupBy);
        for (int i = 0; i < groupBy.size(); i++) {
            if (!groupBy.get(i).contains("->")) {
                groupBy.set(i, newGroupBy.get(i));
            }
        }
        sumKey = transformConditionForLogic(sumKey, className);
        groupBy.add("sum("+sumKey+") as " + sumKey);
        queryWrapper.select(groupBy);
        return logicInstanceService.list(queryWrapper);
    }

    /**
     * 按指定条件查询并分组求和
     * @param condition
     * @param className
     * @param groupByKey
     * @return
     */
    @Override
    public Map<Object, List<JSONObject>> queryAndGroupBy(String condition, String className, String groupByKey) {
        List<JSONObject> dataList = query(condition, className, null);
        Map<Object, List<JSONObject>> resultMap = dataList.stream()
                .collect(Collectors.groupingBy(d->d.getJSONObject("values").get(groupByKey)));
        return resultMap;
    }


    /**
     * 查询分组，并求和
     * @param condition 查询参数
     * @param className 查询参数
     * @param groupBy   分组参数
     * @param sumKey   排序参数
     * @param orderBy   排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> queryGroupAndSum(String condition, String className, List<String> groupBy, String sumKey, String orderBy) {
        List<LogicInstance> list = fetchInstanceList(condition, className, groupBy, sumKey, orderBy);
        return getLogicInsJsonObjectList(list);
    }

    /**
     * 按类名查找实例
     *
     * @param className 类名
     * @return 返回实例表
     */
    public List<LogicInstance> queryByClassName(String className) {
        return this.queryByClassName(className, true,null);
    }
    public List<LogicInstance> queryByClassName(String className, boolean hierFlag,String condition) {
        LambdaQueryWrapper<LogicInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LogicInstance::getClassName, className);
        wrapper.eq(LogicInstance::getPublished, true);
        condition = this.transformConditionForLogic(condition, className);
        wrapper.apply(StringUtils.isNotBlank(condition), condition);
        List<LogicInstance> list = this.logicInstanceService.list(wrapper);
        if (hierFlag) {
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), className);
            list.forEach(l -> {
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), className, l.getId());
                l.setHierModels(hierModels);
                l.setHierInstances(hierInstances);
            });
        }
        return list;
    }

    public List<JSONObject> queryJsonByClassName(String className){
        List<LogicInstance> logicInstances = this.queryByClassName(className);
        return this.getLogicInsJsonObjectList(logicInstances);
    }


    /**
     * 按类名查找实例
     * @param classNameList 类名
     * @return 返回实例表
     */
    public List<JSONObject> queryWithoutHierByclassNameList(List<String> classNameList) {
        LambdaQueryWrapper<LogicInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(LogicInstance::getClassName,classNameList);
        wrapper.eq(LogicInstance::getPublished,true);
        List<LogicInstance> list = logicInstanceService.list(wrapper);
        return getLogicInsJsonObjectList(list);
    }

    /**
     * 根据id获取实例数据
     *
     * @param id 主键id
     * @return 返回实例
     */
    public LogicInstance queryById(Long id) {
        if (id!=null) {
            return this.logicInstanceService.getById(id);
        } else {
            return null;
        }
    }

    /**
     * 根据id获取实例数据及关联的hier数据
     *
     * @param id 主键id
     * @return 返回实例
     */
    public LogicInstance queryInsWithHierById(Long id) {
        if (id!=null) {
            LogicInstance logicInstance = this.logicInstanceService.getById(id);
            if (logicInstance!=null) {
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), logicInstance.getId(),  logicInstance.getClassName(), null);
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), logicInstance.getClassName());
                logicInstance.setHierInstances(hierInstances);
                logicInstance.setHierModels(hierModels);
            }
            return logicInstance;
        } else {
            return null;
        }
    }

    /**
     * 根据id获取实例数据
     *
     * @param ids 主键ids
     * @return 返回实例
     */
    public List<JSONObject> queryByIds(List<Long> ids) {
        LambdaQueryWrapper<LogicInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(LogicInstance::getId,ids);
        List<LogicInstance> logicInstanceList = logicInstanceService.list(wrapper);
        logicInstanceList.forEach(l->{
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), l.getId(),  l.getClassName(), null);
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), l.getClassName());
            l.setHierInstances(hierInstances);
            l.setHierModels(hierModels);
        });
        return getLogicInsJsonObjectList(logicInstanceList);

    }
    /**
     * 根据id获取实例数据
     *
     * @param id 主键id
     * @return 返回实例
     */
    @Override
    public JSONObject queryJsonById(Long id) {
        LogicInstance logicInstance = logicInstanceService.getById(id);
        return getLogicInsJsonObjectList(Arrays.asList(logicInstance)).get(0);
    }

    /**
     * 根据id获取实例数据
     *
     * @param idList 主键id
     * @return 返回实例
     */
    @Override
    public List<JSONObject> queryJsonByIdList(List<Long> idList) {
        List<LogicInstance> logicInstanceList = logicInstanceService.listByIds(idList);
        return getLogicInsJsonObjectList(logicInstanceList);
    }

    /**
     * 更新状态
     * @param id 实例id
     * @param statusCode 状态
     */
    @Override
    public void updateStatus(Long id, String statusCode) {
        LogicInstance logicInstance = queryById(id);
        logicInstance.setSt0(statusCode);
        updateById(logicInstance);
    }

    /**
     * 查询实例容器hier
     *
     * @param id 参数
     * @return 返回hier
     */
    public JSONObject queryHierById(Long id) {
        try {
            LogicInstance logicInstance = this.logicInstanceService.getById(id);
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), logicInstance.getClassName(), Long.valueOf(id));
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), logicInstance.getClassName());
            HierInstanceUtils hierInstanceUtils = new HierInstanceUtils(hierInstances, hierModels);
            return hierInstanceUtils.fetchHier();
        } catch (Exception ex) {
            throw new BusinessException("999999", "查询容器信息失败！");
        }
    }

    /**
     * 按条件分页查询实例摘要
     *
     * @param pageNumber 查询参数
     * @param pageSize   查询参数
     * @param condition  查询参数
     * @param className  查询参数
     * @param orderBy    排序参数
     * @return 返回值
     */
    public PageInfo queryInfoByPage(int pageNumber, int pageSize, String condition, String className, String orderBy, boolean needHier) {
        try {
            Page<LogicInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<LogicInstance> queryWrapper = buildQueryWrapper(condition, className, orderBy);
            return getPageInfoResult(pageInfo, queryWrapper, true, needHier);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 按条件分页查询实例
     *
     * @param pageNumber 查询参数
     * @param pageSize   查询参数
     * @param condition  查询参数
     * @param className  查询参数
     * @param orderBy    排序参数
     * @return 返回值
     */
    public PageInfo queryByPage(int pageNumber, int pageSize, String condition, String className, String orderBy,  boolean needHier) {
        try {
            Page<LogicInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<LogicInstance> queryWrapper = buildQueryWrapper(condition, className, orderBy);
            return getPageInfoResult(pageInfo, queryWrapper, false, needHier);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 按条件分页查询实例
     *
     * @param pageNumber 查询参数
     * @param pageSize   查询参数
     * @param condition  查询参数
     * @param className  查询参数
     * @param orderBy    排序参数
     * @return 返回值
     */
    public PageInfo queryByPage(int pageNumber, int pageSize, String condition, String className, String orderBy, String hierValueCondition) {
        try {
            Page<LogicInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<LogicInstance> queryWrapper = buildQueryWrapper(condition, className, orderBy);
            if (StrUtil.isNotBlank(hierValueCondition)) {
                hierValueCondition = hierValueCondition.replace("'$", "insValues->'$");
            }
            return getPageInfoResult(pageInfo, queryWrapper, false, hierValueCondition);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！", ex);
        }
    }

    /**
     * 按条件分页查询实例
     *
     * @param pageNumber 查询参数
     * @param pageSize   查询参数
     * @param condition  查询参数
     * @param className  查询参数
     * @param orderBy    排序参数
     * @return 返回值
     */
    public PageInfo queryByPageWithoutHier(int pageNumber, int pageSize, String condition, String className, String orderBy) {
        try {
            Page<LogicInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<LogicInstance> queryWrapper = buildQueryWrapper(condition, className, orderBy);
            return getPageInfoResultWithoutHier(pageInfo, queryWrapper, false);
        } catch (Exception ex) {
            throw new BusinessException("999999", "分页无条件查询模型信息！", ex);
        }
    }

    /**
     * 添加模型
     *
     * @param type 参数
     * @param className 参数
     * @param name 参数
     * @return 返回值
     */
    @Override
    public JSONObject add(String type, String className,String name,JSONObject values) {
        LogicInstance instance = buildNewLogicInstance(type, className, name, values);
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        this.add(instance);
        return instance.getInsJsonObject(logicModel);
    }

    /**
     * 保存新实例
     * @param newInstance 新实例
     * @return 返回添加后的实例
     */
    public LogicInstance add(LogicInstance newInstance){
        if (StrUtil.isBlank(newInstance.getName())) {
            newInstance.setName(UuidTool.getUUID32());
        }
        this.logicInstanceService.save(newInstance);
        List<HierInstance> hierInstances = this.hierInstanceDslService.add(ModelType.Logic.getCode(), newInstance.getClassName(), newInstance.getId());
        List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), newInstance.getClassName());
        newInstance.setHierInstances(hierInstances);
        newInstance.setHierModels(hierModels);
        //添加历史
//        LogicInstanceHistory logicInstanceHistory = new LogicInstanceHistory();
//        BeanUtils.copyProperties(newInstance, logicInstanceHistory);
//        logicInstanceHistory.setId(null);
//        logicInstanceHistoryService.save(logicInstanceHistory);
        return newInstance;
    }

    /**
     * 保存新实例
     * @param insJson 新实例Json
     * @return 返回添加后的实例JSON
     */
    public JSONObject add(JSONObject insJson) {
        String className = insJson.getString("className");
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        LogicInstance instance = new LogicInstance(logicModel, insJson);
        this.add(instance);
        return instance.getInsJsonObject(logicModel);
    }

    /**
     * 保存新实例
     * @param insJsonList 新实例Json
     * @return 返回添加后的实例JSON
     */
    public List<JSONObject> batchAdd(List<JSONObject> insJsonList) {
        List<JSONObject> resultList = new ArrayList<>();
        insJsonList.forEach(insJson->{
            JSONObject result = add(insJson);
            resultList.add(result);
        });
        return resultList;
    }

    /**
     * 批量保存或更新实例
     * @param insJsonList 新实例Json
     * @return 返回添加后的实例JSON
     */
    @Override
    public List<JSONObject> batchAddOrUpdate(List<JSONObject> insJsonList) {
        List<JSONObject> updateList = insJsonList.stream().filter(d -> d.get("id") != null).collect(Collectors.toList());
        List<JSONObject> addList = insJsonList.stream().filter(d -> d.get("id") == null).collect(Collectors.toList());
        batchAdd(addList);
        updateByIds(updateList);
        return insJsonList;
    }


    /**
     * 构建新实例数据对象
     *
     * @param className 类名
     * @param name      名称
     * @return 返回构建的新实例
     */
    public LogicInstance buildNewLogicInstance(String className, String name) {
        return this.buildNewLogicInstance("logic", className, name, null);
    }

    /**
     * 构建新实例数据对象
     * @param type 类型
     * @param className 类名
     * @param name 名称
     * @param values 实体值
     * @return 返回构建的新实例
     */
    public LogicInstance  buildNewLogicInstance(String type, String className,String name,JSONObject values){
        if (!existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
        if(values==null){
            values = new JSONObject();
        }

        handleAutoGenValue(values);

        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        JSONObject insJsonObject = new JSONObject();
        insJsonObject.put("type", type);

        insJsonObject.put("name", name);
        insJsonObject.put("className", className);
        insJsonObject.put("published", true);
        insJsonObject.put("version", logicModel.getVersion());
        insJsonObject.put("values", values);
        insJsonObject.put("web", new JSONObject());
        insJsonObject.put("others", new JSONObject());

        return new LogicInstance(logicModel, insJsonObject);
    }


    /**
     * 处理自动生成的字段
     * @param targetValueJson
     */
    @Override
    public void handleAutoGenValue(JSONObject targetValueJson) {
        autoGenUtil.handleAutoGenValue(targetValueJson);
    }

    public LogicInstance  buildNewLogicInstance(JSONObject jsonObject){
        String className = jsonObject.getString("className");
        String type = jsonObject.getString("type");
        if (!existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        return new LogicInstance(logicModel, jsonObject);
    }


    /**
     * 绑定实体到逻辑节点上，如果hier类型是list，需要创建新节点并绑定
     *
     * @param className 静态逻辑类名
     * @param nodeId    要绑定实体所在的节点
     * @param entityId  绑定实体的Id
     * @return 返回结静态逻辑实例json
     */
    public JSONObject bindEntityToHier(Long logicId, String className, String nodeId, Long entityId) {
        LogicModel model = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        JSONObject hierProperties = model.getHierProperties();
        LogicInstance logicInstance = this.logicInstanceService.getById(logicId);
        JSONObject hier = logicInstance.getHier();
        String type = hier.getString("type");
        JSONArray content = hier.getJSONArray("content");
        if(content==null){
            content = new JSONArray();
        }
        switch (type) {
            case "list":
                ListHier listHier = new ListHier(hierProperties);
                List<ListHierContent> listHierContent = listHier.getContent();
                listHierContent.get(0).getLink().put("id", entityId);
                listHierContent.get(0).setId(UuidTool.getUUID32());
                content.add(listHierContent.get(0));
                this.logicInstanceService.updateById(logicInstance);
                return logicInstance.getInsJsonObject(model);
            case "dictionary":
            case "tree":
            case "chain":
            case "treeChain":
                content.forEach(c -> {
                    JSONObject obj = (JSONObject) c;
                    String id = obj.getString("id");
                    if (id.equals(nodeId)) {
                        obj.getJSONObject("link").put("id", entityId);
                    }
                });
                this.logicInstanceService.updateById(logicInstance);
                return logicInstance.getInsJsonObject(model);
            default:
                break;

        }

        return logicInstance.getInsJsonObject(model);
    }

    /**
     * 绑定实体到逻辑节点上，如果hier类型是list，需要创建新节点并绑定
     *
     * @param nodeId   要绑定实体所在的节点
     * @param entityId 绑定实体的Id
     * @return 返回结静态逻辑实例json
     */
    public JSONObject unbindEntityToHier(Long logicId, String nodeId, Long entityId) {
        LogicInstance logicInstance = this.logicInstanceService.getById(logicId);
        LogicModel model = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), logicInstance.getClassName());
        JSONObject hier = logicInstance.getHier();
        String type = hier.getString("type");
        JSONArray content = hier.getJSONArray("content");
        if(content==null){
            content = new JSONArray();
        }
        switch (type) {
            case "list":
                int removeIndex = -1;
                for (int i = 0; i < content.size(); i++) {
                    JSONObject contentJson = content.getJSONObject(i);
                    JSONObject link = contentJson.getJSONObject("link");
                    String id = link.getString("id");
                    if (String.valueOf(entityId).equals(id)) {
                        removeIndex = i;
                    }
                }
                if (removeIndex > -1) {
                    content.remove(removeIndex);
                    hier.put("content",content);
                }
                this.logicInstanceService.updateById(logicInstance);
                return logicInstance.getInsJsonObject(model);
            case "dictionary":
            case "tree":
            case "chain":
            case "treeChain":
                content.forEach(c -> {
                    JSONObject obj = (JSONObject) c;
                    String id = obj.getString("id");
                    if (id.equals(nodeId)) {
                        obj.getJSONObject("link").put("id", "");
                    }
                });
                this.logicInstanceService.updateById(logicInstance);
                return logicInstance.getInsJsonObject(model);
            default:
                break;

        }

        return logicInstance.getInsJsonObject(model);
    }

    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObject 参数
     * @return 返回值
     */
    @Override
    public JSONObject updateById(JSONObject jsonObject) {
        LogicInstance instance = this.buildUpdateInstance(jsonObject);
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), instance.getClassName());
        this.updateById(instance);
        return instance.getInsJsonObject(logicModel);
    }

    /**
     * 更新空值属性字段
     * @param jsonObject 参数
     * @return 返回值
     */
   public void updateFieldNullById(JSONObject jsonObject){
       String className = jsonObject.getString("className");
       Long id = jsonObject.getLong("id");
       LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
       JSONObject values = jsonObject.getJSONObject("values");
       JSONObject features = logicModel.fetchFeatures();
       UpdateWrapper<LogicInstance> updateWrapper = new UpdateWrapper<>();
       // 遍历 JSONObject 对象
       for (String key : features.keySet()) {
           String v = values.getString(key);
           if(StringUtils.isBlank(v)){
               updateWrapper.set(key, null);
           }
       }
       updateWrapper.eq("id",id);
       logicInstanceService.update(updateWrapper);
   }


    /**
     * 批量更新
     * @param className 类名
     * @param jsonDataList 数据
     * @param featureName 可查询字段名
     * @param featureValues 可查询字段值列表
     */
    @Override
   public void updateBatchBy(String className, List<JSONObject> jsonDataList, String featureName,  List<String> featureValues){
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        JSONObject jsonObject = logicModel.fetchFeaturesByName(featureName);
        String fieldName = jsonObject.getString("code");
        QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(fieldName,featureValues);
        List<LogicInstance> updateInstances = new ArrayList<>();
        List<LogicInstance> instances = logicInstanceService.list(queryWrapper);
        if(CollectionUtils.isEmpty(instances)) {
            return;
        }
        instances.forEach(i -> {
            JSONObject insJsonObject = BeanUtil.copyProperties(i, JSONObject.class);
            String fieldValue = insJsonObject.getString(fieldName);
            featureValues.forEach(f -> {
                if (fieldValue.equals(f)) {
                    JSONObject values = jsonDataList.stream().filter(j -> j.getString(featureName).equalsIgnoreCase(f)).findFirst().orElse(null);
                    if (values != null) {
                        JSONObject updateJson = new JSONObject();
                        updateJson.put("id", i.getId());
                        updateJson.put("className", className);
                        updateJson.put("type", ModelType.Logic.getCode());
                        updateJson.put("values", values);
                        LogicInstance logicInstance = new LogicInstance(logicModel, updateJson);
                        updateInstances.add(logicInstance);
                    }
                }
            });
        });

        if (CollectionUtils.isNotEmpty(updateInstances)) {
            this.logicInstanceService.updateBatchById(updateInstances);
        }
    }

    @Override
    public List<JSONObject> updateByCondition(String className, String condition, JSONObject dataJson) {
        List<LogicInstance> logicInstanceList = fetchInstanceList(condition, className);
        List<JSONObject> resultJsonList = new ArrayList<>();
        logicInstanceList.forEach(j -> {
            JSONObject tempDataJson = BeanUtil.copyProperties(dataJson, JSONObject.class);
            tempDataJson.put("id", j.getId());
            tempDataJson.put("className", className);
            JSONObject jsonObject = updateById(tempDataJson);
            resultJsonList.add(jsonObject);

        });
        return resultJsonList;
    }

    /**
     * 更新ids的values某字段为相同的数据，如：更新状态
     *
     * @param data
     * @return
     */
    @Override
    public List<JSONObject> updateByBatchId(JSONObject data) {
        List<JSONObject> resultList = new ArrayList<>();
        JSONArray ids = data.getJSONArray("ids");
        JSONObject values = data.getJSONObject("values");
        for (int i = 0; i < ids.size(); i++) {
            Long id = ids.getLong(i);
            JSONObject instanceJson = new JSONObject();
            instanceJson.put("id", id);
            instanceJson.put("values", values);
            JSONObject result = updateById(instanceJson);
            resultList.add(result);
        }
        return resultList;
    }

    @Override
    public JSONObject deductByCondition(String className, String condition, String dataDeductFieldName, JSONObject dataJson) {
        List<LogicInstance> logicInstanceList = fetchInstanceList(condition, className);
        if (logicInstanceList.size() > 1) {
            throw new BusinessException("需要更新的记录包含多条");
        }
        LogicInstance logicInstance = logicInstanceList.get(0);
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        JSONObject instanceJson = logicInstance.getInsJsonObject(logicModel);
        JSONObject valueJson = instanceJson.getJSONObject("values");
        valueJson.put(dataDeductFieldName, valueJson.getLongValue(dataDeductFieldName) + dataJson.getLongValue(dataDeductFieldName));
        JSONObject resultJson = updateById(instanceJson);
        log.info("更新的记录 = {}", instanceJson);
        return instanceJson;
    }

    public LogicInstance  buildUpdateInstance(JSONObject jsonObject){
        Long id = jsonObject.getLong("id");
        if(id == null){
            throw new BusinessException("999999", "更新id为空操作失败！");
        }

        LogicInstance sourceInstance = logicInstanceService.getById(id);
        if(sourceInstance==null){
            throw new BusinessException("999999", "要更新实例不存在，操作失败！");
        }
        JSONObject sourceInstanceJson = getLogicInsJsonObjectList(Arrays.asList(sourceInstance)).get(0);
        String className = jsonObject.getString("className");
        String type = jsonObject.getString("type");
        if (!existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), sourceInstance.getClassName());
        return new LogicInstance(logicModel,jsonObject,sourceInstanceJson.getJSONObject("values"));
    }

    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * @param logicInstance 参数
     * @return 返回值
     */
    public LogicInstance updateById(LogicInstance logicInstance){
        logicInstanceService.getBaseMapper().updateById(logicInstance);
        List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), logicInstance.getClassName());
        List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), logicInstance.getClassName(), logicInstance.getId());
        logicInstance.setHierInstances(hierInstances);
        logicInstance.setHierModels(hierModels);
        //添加历史
//        LogicInstance newLogicInstance = this.logicInstanceService.getById(logicInstance.getId());
//        LogicInstanceHistory logicInstanceHistory = new LogicInstanceHistory();
//        BeanUtils.copyProperties(newLogicInstance,logicInstanceHistory);
//        logicInstanceHistory.setId(null);
//        this.logicInstanceHistoryService.save(logicInstanceHistory);
        return logicInstance;
    }





    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObjectList 参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> updateByIds(List<JSONObject> jsonObjectList) {
        List<JSONObject> resultJsonList = new ArrayList<>();
        jsonObjectList.forEach(j -> {
            JSONObject jsonObject = this.updateById(j);
            resultJsonList.add(jsonObject);

        });
        return resultJsonList;
    }


    /**
     * 按类型和类名更新模型实例（配置阶段）
     *
     * @param jsonObject 类型
     * @return 返回模型记录
     */
    @Override
    public List<JSONObject> updateClassName(JSONObject jsonObject) {
        String type = jsonObject.getString("type");
        String className = jsonObject.getString("className");
        if (StringUtils.isBlank(type) || StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "更新模型实例：type,className都不能为空！");
        }

        if (!this.existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在，更新模型实例失败！");
        }

        try {
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("type", type);
            queryWrapper.eq("published", true);
            List<LogicInstance> instances = this.logicInstanceService.list(queryWrapper);
            List<JSONObject> resList = new ArrayList<>();
            instances.forEach(ins -> {
                jsonObject.put("id", ins.getId());
                JSONObject upJsonObject = this.updateById(jsonObject);
                resList.add(upJsonObject);
            });
            return resList;
        } catch (Exception ex) {
            throw new BusinessException("999999", "更新模型类型和类名", ex);
        }
    }


    /**
     * 按ids删除模型,同时删除hier中关联和被关联的数据信息
     *
     * @param ids id列表
     * @return 返回结果
     */
    public boolean deleteByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，删除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            queryWrapper.eq("b7", false);
            //删除实例
            this.logicInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByContainerIdList(ModelType.Logic.getCode(), ids);
            this.hierInstanceDslService.deleteByLinkIdList(ModelType.Logic.getCode(), ids);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }
    }

    /**
     * 按className删除实例，并删除hier中关联和被关联的数据信息
     * 1、删除实例、2、删除历史 3、更新redis
     *
     * @param className 模型类名
     * @return 返回值
     */
    @Override
    public boolean deleteByClassName(String className) {
        if (StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "模型类名称不能为空,删除模型实例失败！");
        }
        //删除缓存
        try {
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("published", true);
            //删除模型
            this.logicInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByClassName(ModelType.Logic.getCode(), className);
            this.hierInstanceDslService.deleteByLinkClassName(ModelType.Logic.getCode(), className);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", String.format("删除模型%s失败!", className), ex);
        }
    }

    /**
     * 根据classNames列表批量删除实例数据，并删除hier中关联和被关联的数据信息
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean deleteByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型实例失败！");
        }
        try {
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除实例
            this.logicInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByClassNameList(ModelType.Logic.getCode(), classNames);
            this.hierInstanceDslService.deleteByLinkClassNameList(ModelType.Logic.getCode(), classNames);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "模型类名称列表删除模型失败！");
        }
    }

    /**
     * 按Id 废除模型
     *
     * @param ids 参数
     * @return 返回结果
     */
    public boolean repealByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，废除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            //删除实例
            this.logicInstanceService.remove(queryWrapper);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }

    }

    /**
     * 批量废除
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean repealByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型失败！");
        }
        try {
            QueryWrapper<LogicModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除模型
            this.logicModelService.remove(queryWrapper);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "模型类名称列表删除模型实例失败！");
        }
    }

    /**
     * 获取分页查询
     *
     * @param pageInfo     分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResult(Page<LogicInstance> pageInfo, QueryWrapper<LogicInstance> queryWrapper, boolean isInfo, boolean needHier) {
        Page<LogicInstance> queryPage = logicInstanceService.page(pageInfo, queryWrapper);
        List<LogicInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if (isInfo) {
            jsonObjectList = this.getLogicInsInfoJsonObjectList(records);
        } else {
            if (needHier) {
                records.forEach(r->{
                    List<HierInstance> hierInstances = this.hierInstanceDslService
                            .queryByContainerId(ModelType.Logic.getCode(), r.getClassName(), r.getId());
                    List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), r.getClassName());
                    r.setHierInstances(hierInstances);
                    r.setHierModels(hierModels);
                });
            }
            jsonObjectList = this.getLogicInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * 获取分页查询
     *
     * @param pageInfo     分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResult(Page<LogicInstance> pageInfo, QueryWrapper<LogicInstance> queryWrapper, boolean isInfo, String hierCondition) {
        Page<LogicInstance> queryPage = logicInstanceService.page(pageInfo, queryWrapper);
        List<LogicInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if (isInfo) {
            jsonObjectList = this.getLogicInsInfoJsonObjectList(records);
        } else {
            records.forEach(r->{
                List<HierInstance> hierInstances = hierInstanceDslService.queryByContainerId(ModelType.Logic.getCode(), r.getId(), r.getClassName(), hierCondition);
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Logic.getCode(), r.getClassName());
                r.setHierInstances(hierInstances);
                r.setHierModels(hierModels);
            });
            jsonObjectList = this.getLogicInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * 获取分页查询
     *
     * @param pageInfo     分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResultWithoutHier(Page<LogicInstance> pageInfo, QueryWrapper<LogicInstance> queryWrapper, boolean isInfo) {
        Page<LogicInstance> queryPage = logicInstanceService.page(pageInfo, queryWrapper);
        List<LogicInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if (isInfo) {
            jsonObjectList = this.getLogicInsInfoJsonObjectList(records);
        } else {
            jsonObjectList = this.getLogicInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * 检查模型是否存在
     *
     * @param type      类型
     * @param className 类名称
     * @return 返回是否存，true 存在，false 不存在
     */
    private boolean existModel(String type, String className) {
        QueryWrapper<LogicModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
        queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
        queryWrapper.eq("published", true);
        long count = this.logicModelService.count(queryWrapper);
        return count > 0;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getLogicInsInfoJsonObjectList(List<LogicInstance> instances) {
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            JSONObject infoJsonObject = ins.getInfoJsonObject();
            jsonList.add(infoJsonObject);

        });
        return jsonList;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getLogicInsJsonObjectList(List<LogicInstance> instances) {
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), ins.getClassName());
            JSONObject insJsonObject = ins.getInsJsonObject(logicModel);
            jsonList.add(insJsonObject);
        });
        return jsonList;
    }

    /**
     * 分组条件字段转换
     *
     * @param conditionList 参数
     * @param className 参数
     */
    public List<String> transformConditionListForLogic(List<String> conditionList, String className) {
        if (StringUtils.isBlank(className)) {
            return conditionList;
        }
        LogicModel logicModel = modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        if (logicModel != null) {
            List<String> newGroupBy = conditionList.stream().map(d -> {
                List<JSONObject> featureProperties = logicModel.fetchFeatureProperties();
                for (JSONObject item : featureProperties) {
                    String name = item.getString("name");
                    String code = item.getString("code");
                    d = d.replaceAll(name, code);
                    if (d.equals(name) || d.contains("->")) {
                        break;
                    }
                }
                // insValues->'$.material_code'
                // if (d.startsWith("insValues->")) {
                if (d.contains(" as ")) {
                    d = d.substring(d.indexOf("as") + 2);
                }
                return d;
            }).collect(Collectors.toList());
            return newGroupBy;
        }
        return conditionList;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition 参数
     * @param className 参数
     */
    public String transformConditionForLogic(String condition, String className) {
        if (StringUtils.isBlank(condition)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }
        if (StringUtils.isBlank(className)) {
            return condition;
        }
        if (StringUtils.isNotBlank(className) && StringUtils.isNotBlank(condition)) {
            LogicModel logicModel = modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
            if (logicModel != null) {
                List<JSONObject> featureProperties = logicModel.fetchFeatureProperties();
                for (JSONObject item : featureProperties) {
                    String name = item.getString("name");
                    String code = item.getString("code");
                    // condition = condition.replaceAll(name, code);
                    condition = condition.replaceAll("(?<!['%a-z\\d_\\u4e00-\\u9fa5])"+name, code);
                }
                List<JSONObject> featureNoProperties = logicModel.fetchNonFeaturesProperties();
                for (JSONObject item : featureNoProperties) {
                    String name = item.getString("name");
                    condition = condition.replaceAll("(?<!['%a-z0-9_\\u4e00-\\u9fa5])"+name,
                            java.util.regex.Matcher.quoteReplacement("JSON_EXTRACT(insValues,'$.")+name+
                                    "')");
                }
            }
        }
        return condition;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition 取className 条件
     * @param className 类名
     * @param orderBy   排序参数
     */
    public String transformOrderByForLogic(String condition, String className, String orderBy) {
        if (StringUtils.isBlank(orderBy)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }

        if (StringUtils.isBlank(className)) {
            return orderBy;
        }
        orderBy = orderBy.replaceAll(" ", "");
        LogicModel logicModel = modelCacheDslService.queryModel("logic", className);
        List<JSONObject> featureProperties = logicModel.fetchFeatureProperties();
        for (JSONObject item : featureProperties) {
            String name = item.getString("name");
            String code = item.getString("code");
            orderBy = orderBy.replaceAll(name, code);
        }
        return orderBy;
    }


    /**
     * 根据条件删除实例信息，查询出所有实例id后调用删除根据id删除实例同时删除关联和和被关联的hier数据
     * @param className
     * @param condition
     */
    public void deleteByCondition(String className, String condition) {
        if (StrUtil.isBlank(condition) || StrUtil.isBlank(className)) {
            return;
        }
        List<Long> ids = this.query(condition,className).stream().map(json -> json.getLong("key")).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(ids)){
            return;
        }
        this.deleteByIds(ids);
    }


   public List<LogicInstance> queryFiled(String name,String className, String condition){
       LogicModel logicModel = modelCacheDslService.queryModel("logic", className);
       JSONObject jsonItem = logicModel.fetchFeaturesByName(name);
       String fieldCode = jsonItem.getString("code");
       String fieldType = jsonItem.getString("type");
       List<String> selectionColumn =new ArrayList<>();
       selectionColumn.add(fieldCode);
       QueryWrapper<LogicInstance> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("className", className);
       queryWrapper.apply(condition);
       queryWrapper.select(selectionColumn);

       List<LogicInstance> list = logicInstanceService.list(queryWrapper);
       for (LogicInstance instance : list) {
           try {
               Field field = instance.getClass().getDeclaredField(fieldCode);
               field.setAccessible(true);
               Object oValue = field.get(instance);


           } catch (NoSuchFieldException | IllegalAccessException e) {

           }
       }
       return logicInstanceService.list(queryWrapper);
   }
}
